package ucuserslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetUserNotifyMsgReadLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSetUserNotifyMsgReadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetUserNotifyMsgReadLogic {
	return &SetUserNotifyMsgReadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 设置消息已读
func (l *SetUserNotifyMsgReadLogic) SetUserNotifyMsgRead(in *pb.SetUserNotifyMsgReadReq) (*pb.SetUserNotifyMsgReadResp, error) {
	defer utils.RecoverPanic()

	if in.Id != 0 {
		err := l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
			// 设置消息已读
			err2 := l.svcCtx.UserNotifyMsgModel.UpdateRead(ctx, tx, in.Id, dbkey.Disable)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			// 更新消息条数
			err2 = l.svcCtx.UserNotifyMsgStatModel.DecrMsgCount(ctx, tx, in.Uid, 1)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			return nil
		})
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
		return &pb.SetUserNotifyMsgReadResp{}, nil
	}

	// 设置消息已读
	if in.IsAllRead == dbkey.Enable {
		err := l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
			// 设置消息已读
			err2 := l.svcCtx.UserNotifyMsgModel.UpdateAllRead(ctx, tx, in.Uid, dbkey.Enable, dbkey.Disable)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			// 更新消息条数
			err2 = l.svcCtx.UserNotifyMsgStatModel.UpdateAllRead(ctx, tx, in.Uid)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			return nil
		})
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
	}

	return &pb.SetUserNotifyMsgReadResp{}, nil
}
